/**
 * @param {number[][]} cuboids
 * @return {number}
 */
var maxHeight = function(cuboids) {
    const n = cuboids.length;
    for (const v of cuboids) {
        v.sort((a, b) => a - b);
    }
    cuboids.sort((a, b) => (a[0] + a[1] + a[2]) - (b[0] + b[1] + b[2]));

    const memo = new Array(n).fill(-1)

    const dfs = (cuboids, memo, top, index) => {
        if (index === cuboids.length) {
            return 0;
        }
        if (top !== -1 && memo[top] !== -1) {
            return memo[top];
        }
        let height = dfs(cuboids, memo, top, index + 1);
        if (top === -1 || check(cuboids[top], cuboids[index])) {
            height = Math.max(height, cuboids[index][2] + dfs(cuboids, memo, index, index + 1));
        }
        if (top != -1) {
            memo[top] = height;
        }
        return height;
    }
    return dfs(cuboids, memo, -1, 0);
}

const check = (a, b) => {
    return a[0] <= b[0] && a[1] <= b[1] && a[2] <= b[2];
};


module.exports = maxHeight;